package com.frame.auth.security.authorization;

import com.frame.auth.security.config.AuthServerTokenConfig;
import com.frame.auth.security.config.PasswordConfig;
import com.frame.auth.security.config.WebSecurityConfig;
import com.frame.auth.security.exception.AuthResponseException;
import com.frame.auth.security.filter.CustomClientCredentialsTokenEndpointFilter;
import com.frame.auth.security.handler.AuthAccessDeniedHandler;
import com.frame.auth.security.handler.AuthenticationEntryPointHandler;
import com.frame.auth.security.service.AuthClientDetailsService;
import com.frame.auth.security.service.AuthCodeServices;
import com.frame.auth.security.service.AuthUserDetailsService;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

import javax.annotation.Resource;

/**
 * @auther zhangwj
 * @date 2021/3/10 下午8:18
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final static String DEFAULT_PATH_CONFIRM_ACCESS = "/oauth/confirm_access";

    private final static String CUSTOM_PATH_CONFIRM_ACCESS = "/login/confirm_access";

    @Resource
    private AuthClientDetailsService authClientDetailsService;

    @Resource
    private WebSecurityConfig webSecurityConfig;

    @Resource
    private AuthUserDetailsService authUserDetailsService;

    @Resource
    private AuthCodeServices authCodeServices;

    @Resource
    private PasswordConfig passwordConfig;

    @Resource
    private AuthServerTokenConfig authServerTokenConfig;

    /**
     * 客户端请求配置
     *
     * @param clients 客户端
     * @throws Exception 异常
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(authClientDetailsService);
    }

    /**
     * 认证
     *
     * @param security 认证
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security);
        endpointFilter.afterPropertiesSet();
        endpointFilter.setAuthenticationEntryPoint(new AuthenticationEntryPointHandler());
        security.addTokenEndpointAuthenticationFilter(endpointFilter);

        // 允许表单登录(加了错误验证不能开放)
        // security.allowFormAuthenticationForClients();
        // 自定义异常处理端口
        //security.authenticationEntryPoint(authenticationEntryPoint());
        security.accessDeniedHandler(new AuthAccessDeniedHandler())
                .passwordEncoder(passwordConfig.getPasswordEncoder())
                .tokenKeyAccess("permitAll()")            //oauth/token_key是公开
                .checkTokenAccess("isAuthenticated()");   //oauth/check_token公开
    }

    /**
     * 请求地址配置
     *
     * @param endpoints 地址
     * @throws Exception 异常
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 认证管理
        endpoints.authenticationManager(webSecurityConfig.authenticationManagerBean());
        // 用户管理
        endpoints.userDetailsService(authUserDetailsService);
        // 授权码管理
        endpoints.authorizationCodeServices(authCodeServices);
        // token管理
        endpoints.tokenServices(authServerTokenConfig.getAuthServerToken());
        // 允许认证请求get和post
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // 自定义确认授权页面
        endpoints.pathMapping(DEFAULT_PATH_CONFIRM_ACCESS, CUSTOM_PATH_CONFIRM_ACCESS);
        // 自定义错误页
        // endpoints.pathMapping("/oauth/error", "https://www.baidu.com");
        // 自定义异常
        endpoints.exceptionTranslator(new AuthResponseException());
    }
}
